package com.damie.service.impl;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.damie.config.AliyunOssConfig;
import com.damie.domain.*;
import com.damie.dto.WasteTypeDto;
import com.damie.exception.MyException;
import com.damie.mapper.*;
import com.damie.param.WasteOrderParam;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.damie.common.jwtuilts.JwtUtil;
import com.damie.domain.User;
import com.damie.mapper.UserMapper;
import com.damie.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alon
 * @since 2021-01-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",".jpeg", ".gif", ".png"};
    @Autowired
    private OSS ossClient;// 注入阿里云oss文件服务器客户端
    @Autowired
    private AliyunOssConfig aliyunOssConfig;// 注入阿里云OSS基本配置类

    @Resource
    private WasteMapper wasteMapper;

    @Resource
    private WasteOrderDetailsMapper wodm;

    @Resource
    private WasteOrderMapper wasteOrderMapper;

    @Resource
    private UserAddressMapper userAddressMapper;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate srt;

    @Resource
    private UserAddressMapper uam;
    /**
     * @param
     **/
    @Resource
    private UserMapper mapper;

    /**
     * 废品下单
     * @param wasteOrderParam
     * @return success
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean wasteOrder(WasteOrderParam wasteOrderParam, HttpServletRequest request) {
        WasteOrder wasteOrder = new WasteOrder();
        WasteOrderDetails wasteOrderDetails = new WasteOrderDetails();

        //获取当前登录的token
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseToken(token);
        Object userId = claims.get("userId");
        String id = userId.toString();


        //获取用户
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id",id));//1351500604517670913
        System.out.println(user+"++++++++++++++++++++++++++++");
        wasteOrder.setUserId(user.getUserId());
        wasteOrder.setUserPhone(user.getUserTel());
        //查询出用户的默认地址
        List<UserAddress> userid = uam.selectList(new QueryWrapper<UserAddress>().eq("user_id", user.getUserId()));
        if (ObjectUtils.isEmpty(userid)){
            throw new MyException(20005,"还用户还未添加地址");
        }
        for (int i = 0; i < userid.size(); i++) {
            if (userid.get(i).getAddressStetus() == 1){
                //添加地址id
                wasteOrder.setUserAddressId(userid.get(i).getAddressId());
            }
        }
        wasteOrder.setWasteOrderStatus(1);
        //预约时间
        wasteOrder.setAppointmentTime(new Date());
        //把图片地址放在json里面
        JSONObject jb = new JSONObject();
        for (int i = 0; i < wasteOrderParam.getPicture().length; i++) {
            jb.put("第"+(i+1)+"张",wasteOrderParam.getPicture()[i]);
        }
        wasteOrder.setWasteOrderData(jb.toJSONString());
        //订单留言
        wasteOrder.setWasteOrderMessage(wasteOrderParam.getMessage());

        //查询用户地址

        if (wasteOrderParam.getAddress() != null){
            wasteOrder.setUserAddress(wasteOrderParam.getAddress());
        }

        UserAddress userAddress = userAddressMapper.selectOne(new QueryWrapper<UserAddress>().eq("user_id", user.getUserId()).eq("address_stetus", "1"));
        if (userAddress == null){
            throw new MyException(20015,"你还没有填写一个默认地址");
        }
        wasteOrder.setUserAddress(userAddress.getAddressName());

        wasteOrderMapper.insert(wasteOrder);

        //redis中记录 0=》未接单 1 =》就释放锁取消订单
        srt.opsForValue().set("press:"+wasteOrder.getWasteOrderId(),1+"");
        //设置red字段的过期时间
        srt.expire("press:"+wasteOrder.getWasteOrderId(),30, TimeUnit.MINUTES);

        //查询订单id
        System.out.println(wasteOrder.getWasteOrderId()+"==============================");
        //查询所有废品
        List<WasteTypeDto> wastes = wasteOrderParam.getWastes();
        for (int i=0;i < wastes.size();i++) {
            //废品名字
            String wasteName = wastes.get(i).getWasteName();
            //废品重量
            Integer weight1 = wastes.get(i).getWeight();
            //获取到所有的废品种类
            List<Waste> wasts = wasteMapper.selectList(new QueryWrapper<Waste>().eq("waste_name", wasteName));

            if (ObjectUtils.isEmpty(wasts)){
                throw new MyException(20005,"没有该废品");
            }
            for (int j = 0; j < wasts.size(); j++) {
                //重量
                wasts.get(j).setWeight(weight1);
                //执行修改
                wasteOrderDetails.setWasteId(wasts.get(j).getWasteId());
                wasteOrderDetails.setWasteName(wasts.get(j).getWasteName());
                wasteOrderDetails.setWasteNumber(wasts.get(j).getWeight());
                BigDecimal wastePrice = wasts.get(j).getWastePrice();
                //每个商品计算的价格
                wasteOrderDetails.setWastePrice(wastePrice.multiply(new BigDecimal(weight1)));
                wasteOrderDetails.setWasteOrderId(wasteOrder.getWasteOrderId());
                wasteOrderDetails.setWasteOrderDetailsId(null);
                wodm.insert(wasteOrderDetails);
            }
        }
        return true;
    }
    /**
     * 文件上传
     * @param uploadFile
     * 使用第三方依赖
     * @return
     */
    @Override
    public String uploadPicture(MultipartFile uploadFile) {
        // 获取oss的Bucket名称
        String bucketName = aliyunOssConfig.getBucketName();
        // 获取oss的地域节点
        String endpoint = aliyunOssConfig.getEndPoint();
        // 获取oss的AccessKeySecret
        String accessKeySecret = aliyunOssConfig.getAccessKeySecret();
        // 获取oss的AccessKeyId
        String accessKeyId = aliyunOssConfig.getAccessKeyId();
        // 获取oss目标文件夹
        String filehost = aliyunOssConfig.getFileHost();
        // 返回图片上传后返回的url
        String returnImgeUrl = "";

        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }
        if (!isLegal) {// 如果图片格式不合法
            throw new MyException(20006,"图片格式不合法");
        }
        // 获取文件原名称
        String originalFilename = uploadFile.getOriginalFilename();
        // 获取文件类型
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 新文件名称
        String newFileName = UUID.randomUUID().toString() + fileType;
        // 构建日期路径, 例如：OSS目标文件夹/2020/10/31/文件名
        String filePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        // 文件上传的路径地址
        String uploadImgeUrl = filehost + "/" + filePath + "/" + newFileName;

        // 获取文件输入流
        InputStream inputStream = null;
        try {
            inputStream = uploadFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        /**
         * 下面两行代码是重点坑：
         * 现在阿里云OSS 默认图片上传ContentType是image/jpeg
         * 也就是说，获取图片链接后，图片是下载链接，而并非在线浏览链接，
         * 因此，这里在上传的时候要解决ContentType的问题，将其改为image/jpg
         */
        ObjectMetadata meta = new ObjectMetadata();
        //更改请求头
        meta.setContentType("image/jpg");

        //文件上传至阿里云OSS
        ossClient.putObject(bucketName, uploadImgeUrl, inputStream, meta);
        /**
         * 注意：在实际项目中，文件上传成功后，数据库中存储文件地址
         */
        // 获取文件上传后的图片返回地址
        returnImgeUrl = "http://" + bucketName + "." + endpoint + "/" + uploadImgeUrl;

        return returnImgeUrl;
    }

    /**
     * @param code
     **/
    @Override
    public String qqLogin(String code) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        //获取qq 详细信息
        String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"
                +"&client_id=101780702"
                +"&client_secret=be3cf79b89eafe3f0b8f90462aed8065"
                +"&code="+code
                +"&redirect_uri=http://www.pawntest.com/qqlogin"
                +"&fmt=json";
        //https://graph.qq.com/oauth2.0/token
        String s = restTemplate.getForObject(url, String.class);

        JSONObject jsonObject = JSONObject.parseObject(s);
        Object access_token = jsonObject.get("access_token");
        String user = "https://graph.qq.com/oauth2.0/me?access_token="+access_token.toString()+"&fmt=json";
        String forObject = restTemplate.getForObject(user, String.class);
        JSONObject jsonObject1 = JSONObject.parseObject(forObject);
        Object openid = jsonObject1.get("openid");
        String s1 = "https://graph.qq.com/user/get_user_info?"
                +"access_token="+access_token.toString()+"&oauth_consumer_key=101780702&openid="+openid.toString();
        String forObject1 = restTemplate.getForObject(s1, String.class);
        System.out.println(forObject1);
        JSONObject jsonObject2 = JSONObject.parseObject(forObject1);


        User user1 = selectUser(openid.toString());
        Map<String,Object> openid2 = new HashMap();
        if (ObjectUtils.isEmpty(user1)){
            //如果是空的说明没有注册 进行注册
            String sta = addUser(openid.toString(), jsonObject2.get("figureurl_qq_2").toString(),jsonObject2);
            if (!"".equals(sta)&&sta!=null){
                //成功则前往获取token
                openid2.put("userId",sta);
                openid2.put("openid", openid);
                String token = JwtUtil.createToken(openid2,1200);
                return token;
            }
            throw new RuntimeException("新增失败");
        }
        //如果不是空的说明已经注册，直接返回true
        openid2.put("userId",user1.getUserId());
        openid2.put("openid", openid);
        String token = JwtUtil.createToken(openid2,1200);
        return token;
    }
    public User selectUser(String openid)throws Exception{
        //通过唯一的openid 查看数据库是否有相同的user_account
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_account", openid);
        User user1 = mapper.selectOne(queryWrapper);
        return user1;
    }
    /**
     * @param openid
     * @param url img
     * */
    public String addUser(String openid,String url,JSONObject jsonObject2)throws Exception{
        //注册新用户数据
        User user2 = new User();
        user2.setUserAccount(openid.toString());
        user2.setUserStatus(1);
        user2.setUserRole(1);
        user2.setUserPicture(url);
        user2.setUserPassword(jsonObject2.get("nickname").toString());
        user2.setSalt(jsonObject2.get("gender").toString());
        BigDecimal bigDecimal = new BigDecimal(0);
        user2.setUserIncome(bigDecimal);
        int insert = mapper.insert(user2);
        if (insert>0){
            System.out.println("注册成功");
            return user2.getUserId();
        }
        return null;
    }
}
